package com.xiangxiangjd.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.xiangxiangjd.bean.SysDict;
import com.xiangxiangjd.controller.entity.ApiCode;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.controller.model.ApiResultModel;
import com.xiangxiangjd.utils.FtpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ClientInfoStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author 肖守凯
 * @packge com.xbxkj.admin.CountryPushController
 * @data 2019-09-02 16:15
 * @project DaTa-Show
 */
@Controller
@RequestMapping("/")
@Api(tags = "服务API")
@Slf4j
public class IndexController extends BaseController {


    /**
     * 进入系统 登陆页
     */
    @GetMapping("/login.html")
    public String loginHtml() {
        return "login";
    }

    /**
     * 进入系统 首页
     */
    @GetMapping("/index.html")
    public String indexHtml(Model model) {
        model.addAttribute("user", getUser());
        //rabbitTemplate.convertAndSend("report",getUser());

        return "index";
    }

    // 允许上传的文件类型
    private static final List<String> RESUME_TYPES = new ArrayList<>();

    //允许上传的格式
    static {
//        RESUME_TYPES.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        RESUME_TYPES.add("application/pdf");
//        RESUME_TYPES.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        RESUME_TYPES.add("application/msword");
//        RESUME_TYPES.add("image/gif");
        RESUME_TYPES.add("image/jpeg");
        RESUME_TYPES.add("image/png");

    }

    // 上传文件大小的上限值
    @Value("${project.resume.max-size}")
    private int resumeMaxSize;


    /**
     * 上传图片
     *
     * @return
     * @throws Exception
     * @paramle
     */
    //@PreAuthorize("hasRole('ROLE_USER')")
    @PostMapping(value = "/equipment/setImg")
    @ResponseBody
    @ApiOperation(value = "上传图片", notes = "上传图片", produces = "application/json")
    public ApiResultModel<String> setImg(MultipartFile file) {

        System.out.println("上传了简历");

        String imgUrl = "";

        try {
            if (file.isEmpty()) {
                return $.error("请选择要上传的简历");
            }


            // 检查上传的文件大小
//            if (file.getSize() > resumeMaxSize) {
//
//                return $.error("不允许上传超过" + resumeMaxSize / 1024 + "KB的文件");
//
//
//            }

            // 检查上传的文件类型：image/jpeg, image/png


            if (!RESUME_TYPES.contains(file.getContentType())) {

                return $.error("您上传的头像类型超出了限制，允许上传的文件类型有：" + RESUME_TYPES);

            }


            // 文件先上传至 服务器 返回文件名称
            imgUrl = FtpUtil.uploadFile(file);

            System.out.println("文件名为:" + imgUrl);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("抛出了异常,删除文件文件后 会报出 空指针异常!");
            return $.error(ApiCode.error, "小伙子你代码写错了");
        }

        return $.success(ApiCode.success, ApiCode.success_msg, imgUrl);
    }


    /**
     * 生成图像验证码
     *
     * @param
     * @throws IOException
     */
    @GetMapping(value = "/getCaptcha")
    @ResponseBody
    public void getCode(HttpServletResponse resp, HttpServletRequest request, HttpSession session) {


        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
        //得到code
        String code = captcha.getCode();
        //放到session
        session.setAttribute("code", code);
        System.out.println("获取了一次验证码：" + session.getAttribute("code"));
        //输出流
        ServletOutputStream outputStream = null;
        try {
            outputStream = resp.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读写输出流
        // outputStream.write(captcha.getImageBytes());
        captcha.write(outputStream);
        //关闭输出流

    }


    static ExecutorService executorService = Executors.newFixedThreadPool(2);


    /**
     * 测试多线程调用接口
     *
     * @param
     * @throws IOException
     */
    @GetMapping(value = "/test")
    @ResponseBody
    public Object test() {


        //开始时间
        long start = System.currentTimeMillis();



//        List<SysDict> SysDictList = new ArrayList<>();
//
//        Callable<Boolean> objectCallable = new Callable<Boolean>() {
//
//            @Override
//            public Boolean call() throws Exception {
//
//                for (int i = 0; i < 1000; i++) {
//
//                    SysDict sysDict = new SysDict();
//
//                    sysDict.setK(i + "");
//                    sysDict.setType(i + "");
//                    sysDict.setVal(i + "");
//                    SysDictList.add(sysDict);
//                }
//
//                boolean b = sysDictService.saveBatch(SysDictList);
//
//                return b;
//            }
//        };
//
//        executorService.submit(objectCallable);
//        System.out.println("第一次是否插入成功：" + objectCallable.toString());
//
//        SysDictList.clear();
//
//        Callable<Boolean> objectCallable1 = new Callable<Boolean>() {
//
//            @Override
//            public Boolean call() throws Exception {
//
//                for (int i = 1000; i < 2000; i++) {
//
//                    SysDict sysDict = new SysDict();
//                    sysDict.setK(i + "");
//                    sysDict.setType(i + "");
//                    sysDict.setVal(i + "");
//                    SysDictList.add(sysDict);
//
//                }
//                boolean b = sysDictService.saveBatch(SysDictList);
//
//                return b;
//            }
//        };
//
//        //放入线程池
//        executorService.submit(objectCallable1);
//
//        System.out.println("第二次是否插入成功：" + objectCallable.toString());
        //查询结束时间



        Callable<Object> objectCallable = new Callable<Object>() {

            @Override
            public Object call() throws Exception {

                List<SysDict> list = sysDictService.list();
                log.info(list.toString());


                return list;
            }
        };

        Future<Object> submit = executorService.submit(objectCallable);

        log.info(objectCallable.toString());


        Callable<List<SysDict>> objectCallable1 = new Callable<List<SysDict>>() {

            @Override
            public List<SysDict> call() throws Exception {

                List<SysDict> list = sysDictService.list();
                log.info(list.toString());


                return list;
            }
        };

        Future<Object> submit1 = executorService.submit(objectCallable);

        log.info(objectCallable.toString());

        long end = System.currentTimeMillis() - start;




        log.info("接口执行的时间为:" + end);

        List<Object> objects = new ArrayList<>();




        return objects;

    }


}
